﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using SharedLibraries;
using SharedLibraries.Constants;
using EntityObject;
using DataAccessObject;
using ThangNM_LIB.FUNC;
using System.Web.Security;
using ThangNM_LIB.DB;

namespace ThangNM.UserControl
{
    public partial class Category_DetailUC : System.Web.UI.UserControl
    {
        #region "Properties & Event"
        public delegate void CustomerEventHandler(object sender, CustomerEventArgs args);
        public event CustomerEventHandler ViewMessage;
        public event EventHandler BackList;

        public Int16 iFunctionType
        {
            get { return (Int16)ViewState["iFunctionType"]; }
            set { ViewState["iFunctionType"] = value; }
        }

        public CategoryEO objTemp
        {
            get { return (CategoryEO)ViewState["objTemp"]; }
            set { ViewState["objTemp"] = value; }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    ToolBarUC1.ViewGroupButtonByFunction(ConstEx.funcButtonToolBar.DETAIL);
                }
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        public void BindDataDetail(CategoryEO objInput, Int16 iFuncType)
        {
            objTemp = objInput;
            BindData_DropDownList();
            WebEx.setSelect_DropDownList(ddlFK_iAccountID, Convert.ToString(objInput.FK_iAccountID));
            txtsTitle.Text = objInput.sTitle;
            //txtsContent.Text = objInput.sContent;
            txtsDescription.Text = objInput.sDescription;
            txtsKeyword.Text = objInput.sKeyword;
            //txtsLinkMedia.Text = objInput.sLinkMedia;
            txtsLinkImage.Text = objInput.sLinkImage;
            txtsLinkImageThumbnail.Text = objInput.sLinkImageThumbnail;
            txtsUrlRewrite.Text = objInput.sUrlRewrite;
            txtsUrlShort.Text = objInput.sUrlShort;
            WebEx.setText_InputDefault(txtfPriority, Convert.ToString(objInput.fPriority), "0.5");
            WebEx.setSelect_DropDownList(ddliChangefreq, Convert.ToString(objInput.iChangefreq));
            WebEx.setSelect_DropDownList(ddliRobots, Convert.ToString(objInput.iRobots));
            chkbStatus.Checked = objInput.bStatus;
            WebEx.setText_InputDateTime(txttDateTimeCreate, objInput.tDateTimeCreate);
            WebEx.setText_InputDateTime(txttDateTimeModify, objInput.tDateTimeModify);
            ddlFK_iCategoryID.SelectedValue = Convert.ToString(objInput.FK_iCategoryID);
            txtFK_sTopicID.Text = Convert.ToString(objInput.FK_sTopicID);
            ddliType.SelectedValue = Convert.ToString(objInput.iType);
            iFunctionType = iFuncType;
            ViewByFunction(iFunctionType);
            if (objInput.iType == ConstEx.TableID_C.Other)
            {
                txtsUrlRewrite.Enabled = true;
                txtsUrlShort.Enabled = true;
                txtsTitle.Enabled = true;
            }
        }

        protected void BindData_DropDownList()
        {
            ddlFK_iAccountID.DataSource = (new ShareDAO.UserDAO()).SelectBy_bState(null);
            ddlFK_iAccountID.DataValueField = "PK_iAccountID";
            ddlFK_iAccountID.DataTextField = "sUsername";
            ddlFK_iAccountID.DataBind();

            ddliChangefreq.DataSource = GetListConstants.Changefreq_GLC();
            ddliChangefreq.DataValueField = "Key";
            ddliChangefreq.DataTextField = "Value";
            ddliChangefreq.DataBind();

            ddliRobots.DataSource = GetListConstants.Robots_GLC();
            ddliRobots.DataValueField = "Key";
            ddliRobots.DataTextField = "Value";
            ddliRobots.DataBind();

            //DataTable dt = CategoryDAO.SelectBy_bStatus(BIT.True);
            //foreach (DataRow dr in dt.Rows)
            //{
            //    if (dr["iParentID"].ToString() != "0")
            //    {
            //        switch (dr["iParentID"].ToString().Length)
            //        {
            //            case 1: dr["sName"] = "- " + dr["sName"]; break;
            //            case 2: dr["sName"] = "- - " + dr["sName"]; break;
            //            case 3: dr["sName"] = "- - - " + dr["sName"]; break;
            //            case 4: dr["sName"] = "- - - - " + dr["sName"]; break;
            //        }
            //    }
            //}
            //List<CategoryEO> lst = new List<CategoryEO>();
            //CategoryEO objNew = new CategoryEO();
            //lst = (List<CategoryEO>)ConvertEx.ConvertDataTableToListObject<CategoryEO>(dt, "CategoryEO", lst.GetType());
            //lst.Add(objNew);
            List<Category_ZipEO> lst = new List<Category_ZipEO>();
            Category_ZipEO obj = new Category_ZipEO();
            obj.PK_iCategoryID = 0;
            obj.sName = "";
            lst.Add(obj);
            ddlFK_iCategoryID.DataSource = lst;
            ddlFK_iCategoryID.DataValueField = "PK_iCategoryID";
            ddlFK_iCategoryID.DataTextField = "sName";
            ddlFK_iCategoryID.DataBind();

            ddliType.DataSource = GetListConstants.Category_iType_GLC();
            ddliType.DataValueField = "Key";
            ddliType.DataTextField = "Value";
            ddliType.DataBind();
        }

        protected bool CheckInput()
        {
            string strNull = "";
            if (string.IsNullOrEmpty(txtsTitle.Text) == true)
            {
                strNull += ", " + lblsTitle.Text;
                txtsTitle.Focus();
            }

            if (String.IsNullOrEmpty(strNull))
            {
                return true;
            }
            else
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, MessagesEx.CAC_TRUONG_BAT_BUOC_PHAI_NHAP + strNull.Substring(2).Replace(":", ""), null));
                return false;
            }
        }

        protected void GetObject(ref CategoryEO _CategoryEO)
        {
            try
            {
                _CategoryEO.PK_iTable = ConstEx.TableID_C.Category;
                _CategoryEO.PK_iSEO = objTemp.PK_iSEO;
                _CategoryEO.FK_sAccount = ShareDAO.UserDAO.getPK_iAccountID(Convert.ToString(Session["secret"])).Name;
                _CategoryEO.FK_sCategory = ",";
                _CategoryEO.sTitle = Convert.ToString(txtsTitle.Text);
                _CategoryEO.sKeyword = StringEx.remove_dublicate_in_string_array(txtsKeyword.Text);
                _CategoryEO.sDescription = Convert.ToString(txtsDescription.Text);
                ////_CategoryEO.sLinkMedia = OtherEx.getUrlStandard(txtsLinkMedia.Text);
                _CategoryEO.sLinkImage = OtherEx.getUrlStandard(txtsLinkImage.Text);
                _CategoryEO.sLinkImageThumbnail = OtherEx.getUrlStandard(txtsLinkImageThumbnail.Text);
                //_CategoryEO.sSourceCode = "";
                _CategoryEO.iChangefreq = Convert.ToInt16(ddliChangefreq.SelectedValue);
                _CategoryEO.iRobots = Convert.ToInt16(ddliRobots.SelectedValue);
                _CategoryEO.fPriority = Convert.ToDouble(txtfPriority.Text);
                _CategoryEO.bStatus = chkbStatus.Checked;
                _CategoryEO.iStatus = ConvertEx.Convert_bStatus_iStatus(_CategoryEO.bStatus);

                _CategoryEO.FK_iCategoryID = Convert.ToInt16(ddlFK_iCategoryID.SelectedValue);
                _CategoryEO.FK_iAccountID = ShareDAO.UserDAO.getPK_iAccountID(Convert.ToString(Session["secret"])).Version;
                _CategoryEO.FK_sTopicID = StringEx.getDefaultArrayInDB(objTemp.FK_sTopicID);
                _CategoryEO.iType = Convert.ToInt16(ddliType.SelectedValue);
                _CategoryEO.sNameNonUnicode = RewriteUrl.ConvertToUnSign(txtsTitle.Text).ToLower();


                if (_CategoryEO.iType == ConstEx.TableID_C.Other)
                {
                    _CategoryEO.sUrlRewrite = OtherEx.RemoveDomainInUrl(txtsUrlRewrite.Text);
                    _CategoryEO.sUrlShort = OtherEx.RemoveDomainInUrl(txtsUrlShort.Text);
                }
                else
                {
                    _CategoryEO.sUrlRewrite = Commons.get_sUrlRewrite_sUrlShort(_CategoryEO.PK_iTable, true, null, _CategoryEO.sTitle, _CategoryEO.iType);
                    _CategoryEO.sUrlShort = Commons.get_sUrlRewrite_sUrlShort(_CategoryEO.PK_iTable, false, null, _CategoryEO.sTitle, _CategoryEO.iType);
                }
            }
            catch (Exception ex)
            {
                _CategoryEO = null;
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        protected void ViewByFunction(Int16 iFuncType)
        {
            setEnableAllInput();
            switch (iFuncType)
            {
                case ConstEx.FunctionType.Insert:
                    ddlFK_iCategoryID.Enabled = true;
                    ddliType.Enabled = true;
                    txtsTitle.Enabled = true;
                    chkbStatus.Enabled = true;
                    ToolBarUC1.ViewButtonByFunction(iFunctionType);
                    //trID.Visible = false;
                    break;
                case ConstEx.FunctionType.Update: break;
                case ConstEx.FunctionType.Delete: break;
                case ConstEx.FunctionType.View:
                    chkbStatus.Enabled = true;
                    ToolBarUC1.ViewButtonByFunction(iFunctionType);
                    //trID.Visible = true;
                    break;
            }
        }

        protected void setEnableAllInput()
        {
            ddlFK_iAccountID.Enabled = false;
            //txtPK_iCategoryID.Enabled = false;
            ddlFK_iCategoryID.Enabled = false;
            txtFK_sTopicID.Enabled = false;
            ddliType.Enabled = false;
            txtsTitle.Enabled = false;
            chkbStatus.Enabled = false;
            //trID.Visible = false;
            txtsUrlRewrite.Enabled = false;
            txtsUrlShort.Enabled = false;
            txttDateTimeCreate.Enabled = false;
            txttDateTimeModify.Enabled = false;
        }

        protected void EventButtonToolBar_Click(object sender, CustomerEventArgs e)
        {
            if (e.iType != ConstEx.funcButtonToolBar.BACK_LIST && (new ShareDAO.UserDAO()).SelectBy_sPermission(Session["secret"], Convert.ToString(Request.Url.AbsolutePath), e.iType) == false)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.DANGER, MessagesEx.Khong_Co_Quyen_Truy_Cap, null));
                Commons.setAccessDenied(Page, null);
                return;
            }
            switch (e.iType)
            {
                case ConstEx.funcButtonToolBar.INSERT_LIST: break;
                case ConstEx.funcButtonToolBar.INSERT_ITEM:
                    InsertItem();
                    break;
                case ConstEx.funcButtonToolBar.UPDATE_ITEM:
                    UpdateItem();
                    break;
                case ConstEx.funcButtonToolBar.DELETE_LIST: break;
                case ConstEx.funcButtonToolBar.DELETE_ITEM:
                    DeleteItem();
                    break;
                case ConstEx.funcButtonToolBar.REFRESH_LIST: break;
                case ConstEx.funcButtonToolBar.EXPORT_EXCEL: break;
                case ConstEx.funcButtonToolBar.RESET_FORM:
                    ResetForm();
                    break;
                case ConstEx.funcButtonToolBar.BACK_LIST:
                    if (BackList != null)
                        BackList(this, null);
                    break;
            }
        }

        protected void InsertItem()
        {
            try
            {
                if (CheckInput() == true)
                {
                    CategoryEO _CategoryEO = new CategoryEO();
                    GetObject(ref _CategoryEO);
                    if (_CategoryEO == null)
                        return;
                    if ((new CategoryDAO()).Insert_Update_Delete(ref _CategoryEO, 1) == true)
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Them_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.Category, _CategoryEO.PK_iSEO, _CategoryEO.sTitle), null));
                    }
                    else
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Them_That_Bai_Ma_Ten, ConstEx.Table_Name_C.Category, _CategoryEO.PK_iSEO, _CategoryEO.sTitle), null));
                    }
                }
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }
        protected void UpdateItem()
        {
            try
            {
                if (CheckInput() == true)
                {
                    CategoryEO _CategoryEO = new CategoryEO();
                    GetObject(ref _CategoryEO);
                    if (_CategoryEO == null)
                        return;
                    if (new CategoryDAO().Insert_Update_Delete(ref _CategoryEO, 2) == true)
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Sua_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.Category, _CategoryEO.PK_iSEO, _CategoryEO.sTitle), null));
                    }
                    else
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Sua_That_Bai_Ma_Ten, ConstEx.Table_Name_C.Category, _CategoryEO.PK_iSEO, _CategoryEO.sTitle), null));
                    }
                }
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }
        protected void DeleteItem()
        {
            try
            {
                if (!String.IsNullOrEmpty(objTemp.FK_sTopicID))
                {
                    setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, "Không thể xóa vì danh mục đã được dùng: " + objTemp.FK_sTopicID, null));
                    return;
                }
                CategoryEO _CategoryEO = new CategoryEO();
                GetObject(ref _CategoryEO);
                if (_CategoryEO == null)
                {
                    setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, "Lỗi", null));
                    return;
                }
                if (new CategoryDAO().Insert_Update_Delete(ref _CategoryEO, 3) == true)
                {
                    setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Xoa_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.Category, _CategoryEO.PK_iSEO, _CategoryEO.sTitle), null));
                }
                else
                {
                    setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Xoa_That_Bai_Ma_Ten, ConstEx.Table_Name_C.Category, _CategoryEO.PK_iSEO, _CategoryEO.sTitle), null));
                }
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }
        protected void ResetForm()
        {
            CategoryEO _CategoryEO = new CategoryEO();
            BindDataDetail(_CategoryEO, iFunctionType);
        }

        public void setViewMessage(object sender, CustomerEventArgs args)
        {
            if (ViewMessage != null)
                ViewMessage(sender, args);
        }
    }
}